﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using iSteam.Sdk.Data;

namespace iSteam.Sdk
{
    public class BaseRequest
    {
        internal int Message;
        internal AccessToken _accessToken;
        internal LoginToken _loginToken;

        public BaseRequest(AccessToken accessToken, LoginToken loginToken)
        {
            _accessToken = accessToken;
            _loginToken = loginToken;
        }

        public BaseRequest()
        {

        }

        internal String SteamRequest(String get, String post = null, Source source = Source.Mobile)
        {
            ServicePointManager.Expect100Continue = false;

            string url = string.Format(source == Source.Mobile ? Constants.ServerUrl : Constants.CommunityDataUrl, get);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Host = source == Source.Mobile ? "api.steampowered.com:443" : "steamcommunity.com";
            request.ProtocolVersion = HttpVersion.Version11;
            request.Accept = "*/*";

            if (source == Source.Mobile)
            {
                request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
                request.Headers[HttpRequestHeader.AcceptLanguage] = "en-us";
            }

            //request.UserAgent = "Steam 1291812 / iPhone";
            request.UserAgent = "Valve/Steam HTTP Client 1.0";
            if (post != null)
            {
                request.Method = "POST";
                byte[] postBytes = Encoding.ASCII.GetBytes(post);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Close();
                
                Message++;
            }

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                if ((int)response.StatusCode != 200) return null;

                String src = new StreamReader(response.GetResponseStream()).ReadToEnd();
                response.Close();
                return src;
            }
            catch (WebException e)
            {
                return null;
            }
        }

        public int MessageCount
        {
            get { return Message; }
        }

        public AccessToken AccessToken
        {
            get { return _accessToken; }
        }

        public LoginToken LoginToken
        {
            get { return _loginToken; }
        }
    }
}